﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ProyectoAlmacen.Models;
using ProyectoAlmacen.Negocio;
using System.Text;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;

namespace ProyectoAlmacen.Controllers
{
    public class MaterialController : Controller
    {
        public static MaterialServiceImpl materialService { get; set; }
        

        public ActionResult Index()
        {

            //materialService = new MaterialServiceImpl();
            //ICollection<Material> model = materialService.ListarMaterial();

            HttpWebRequest req2 = (HttpWebRequest)WebRequest
            .Create("http://localhost:64660/Materiales.svc/Materiales");
            req2.Method = "GET";
            HttpWebResponse res2 = (HttpWebResponse)req2.GetResponse();
            StreamReader reader2 = new StreamReader(res2.GetResponseStream());
            string materialJson2 = reader2.ReadToEnd();
            JavaScriptSerializer js2 = new JavaScriptSerializer();
            ICollection<Material> model = js2.Deserialize<ICollection<Material>>(materialJson2);
            return View(model);
        }

        //
        // GET: /Material/Details/5

        public ActionResult Details(int id)
        {
            //Material model = materialService.ObtenerMaterial(id);
            HttpWebRequest req2 = (HttpWebRequest)WebRequest
            .Create("http://localhost:64660/Materiales.svc/Materiales/" + id.ToString());
            req2.Method = "GET";
            HttpWebResponse res2 = (HttpWebResponse)req2.GetResponse();
            StreamReader reader2 = new StreamReader(res2.GetResponseStream());
            string materialJson2 = reader2.ReadToEnd();
            JavaScriptSerializer js2 = new JavaScriptSerializer();
            Material model = js2.Deserialize<Material>(materialJson2);
            return View(model);
        }

        //
        // GET: /Material/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Material/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                string idMaterial = collection["idMaterial"];
                string Descripcion = collection["Descripcion"];
                string Estado = collection["Estado"];
                string idUsuario = collection["idUsuario"];

                if (idMaterial == "" || Descripcion =="" || Estado == "" || idUsuario == "")
                {
                    TempData["ValidacionMaterial"] = "Por favor ingrese los datos completos";
                    return RedirectToAction("Create");

                }
                

                //****************UTILIZANDO REST********************

                
                string postdata = "{\"idMaterial\":\"" + collection["idMaterial"] + "\",\"Descripcion\":\""+collection["Descripcion"]+"\",\"Estado\":\""+collection["Estado"]+"\",\"idUsuario\":\""+collection["idUsuario"]+"\"}";
                byte[] data = Encoding.UTF8.GetBytes(postdata);
                HttpWebRequest req = (HttpWebRequest)WebRequest
                    .Create("http://localhost:64660/Materiales.svc/Materiales");
                req.Method = "POST";
                req.ContentLength = data.Length;
                req.ContentType = "application/json";
                var reqStream = req.GetRequestStream();
                reqStream.Write(data,0,data.Length);
                var res = (HttpWebResponse)req.GetResponse();
                

                //************************************

                return RedirectToAction("Index");
            }
            catch (WebException e)
            {
                HttpWebResponse resError = (HttpWebResponse)e.Response;
                StreamReader readerError = new StreamReader(resError.GetResponseStream());
                string mensajeError = readerError.ReadToEnd();
                JavaScriptSerializer jsError = new JavaScriptSerializer();
                Error mensajeObtenido = jsError.Deserialize<Error>(mensajeError);
                TempData["Mensaje"]= mensajeObtenido.Mensaje;
                return View();
            }
        }
        
        //
        // GET: /Material/Edit/5
 
        public ActionResult Edit(int id)
        {
            //Material model = materialService.ObtenerMaterial(id);

            HttpWebRequest req2 = (HttpWebRequest)WebRequest
            .Create("http://localhost:64660/Materiales.svc/Materiales/" + id.ToString());
            req2.Method = "GET";
            HttpWebResponse res2 = (HttpWebResponse)req2.GetResponse();
            StreamReader reader2 = new StreamReader(res2.GetResponseStream());
            string materialJson2 = reader2.ReadToEnd();
            JavaScriptSerializer js2 = new JavaScriptSerializer();
            Material model = js2.Deserialize<Material>(materialJson2);
            return View(model);
        }

        //
        // POST: /Material/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                
                //***************UTILIZANDO PUT*****************


                string postdata3 = "{\"idMaterial\":\"" + collection["idMaterial"] + "\",\"Descripcion\":\"" + collection["Descripcion"] + "\",\"Estado\":\"" + collection["Estado"] + "\",\"idUsuario\":\"" + collection["idUsuario"] + "\"}";
                byte[] data3 = Encoding.UTF8.GetBytes(postdata3);
                HttpWebRequest req3 = (HttpWebRequest)WebRequest
                    .Create("http://localhost:64660/Materiales.svc/Materiales");
                req3.Method = "PUT";
                req3.ContentLength = data3.Length;
                req3.ContentType = "application/json";
                var reqStream3 = req3.GetRequestStream();
                reqStream3.Write(data3, 0, data3.Length);
                var res3 = (HttpWebResponse)req3.GetResponse();


                //**********************************************
                
                return RedirectToAction("Index");
            }
            catch(WebException e)
            {
                HttpWebResponse resError = (HttpWebResponse)e.Response;
                StreamReader readerError = new StreamReader(resError.GetResponseStream());
                string mensajeError = readerError.ReadToEnd();
                JavaScriptSerializer jsError = new JavaScriptSerializer();
                Error mensajeObtenido = jsError.Deserialize<Error>(mensajeError);
                TempData["Mensaje"] = mensajeObtenido.Mensaje;
                return View();
            }
        }

        //
        // GET: /Material/Delete/5
 
        public ActionResult Delete(int id)
        {
            //Material model = materialService.ObtenerMaterial(id);
            HttpWebRequest req2 = (HttpWebRequest)WebRequest
            .Create("http://localhost:64660/Materiales.svc/Materiales/" + id.ToString());
            req2.Method = "GET";
            HttpWebResponse res2 = (HttpWebResponse)req2.GetResponse();
            StreamReader reader2 = new StreamReader(res2.GetResponseStream());
            string materialJson2 = reader2.ReadToEnd();
            JavaScriptSerializer js2 = new JavaScriptSerializer();
            Material model = js2.Deserialize<Material>(materialJson2);
            return View(model);
        }

        //
        // POST: /Material/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                
                //Material material = new Material();
                //material = materialService.ObtenerMaterial(id);
                //materialService.EliminarMaterial(material);

                //************** HTTP DELETE *************


                HttpWebRequest req4 = (HttpWebRequest)WebRequest
                    .Create("http://localhost:64660/Materiales.svc/Materiales/" + id.ToString());
                req4.Method = "DELETE";
                HttpWebResponse res4 = (HttpWebResponse)req4.GetResponse();
                StreamReader reader4 = new StreamReader(res4.GetResponseStream());

                //****************************************


                return RedirectToAction("Index");
            }
            catch (WebException e)
            {
                return View();
            }
        }
    }
}
